from django import template
from django import forms
from django.http import HttpResponseRedirect
from pirateissues.models import Topic, Issue
from pirateargumentation.models import Argument, Stance

from native_tags.decorators import block
from genericview.views import HttpRedirectException, namespace_get
from pirateissues.models import Topic, Issue

get_namespace = namespace_get('pp_argumentation')

@block
def pp_get_argument_list(context, nodelist, *args, **kwargs):
    """This block tag grabs a list of arguments, based on the issue
    that is paseed into the context and then places the lsit of arguments
    into the context.
    
    Can be used in the following manner:
    {% pp_get_argument_list issue=issue rng=request.rng %}
       Do stuff with {{ pp_argumentation.argument_list }}
    {% endpp_get_argument_list %}
    """
    #TODO:Split argument list into list of argument lists by Stance  
    context.push()
    namespace = get_namespace(context)
    issue = kwargs.pop('issue', None)
    rng = kwargs.pop('rng', None)
    if isinstance(rng, basestring):
        try:
            rng = rng.strip("()").split(",")
            rng = (int(rng[0]), int(rng[1]))
        except:
            rng = None
        if not rng or len(rng) != 2:
            raise ValueError("The argument 'rng='"+ str(rng) + " to the pp_argument_list tag must be "
                             "provided either in the form of an (int, int) pair, or "
                             "as a string in the form of '(<int>, <int>)'.")
    if issue and isinstance(issue, Issue):
        arg_list = Argument.objects.filter(parent__id=issue.id).order_by('-pub_date')
    if rng:
        arg_list = arg_list[rng[0]:rng[1]]
    
    namespace['arg_list'] = arg_list
    output = self._nodelist.render(context)
    context.pop()
    return output

@block
def pp_argument_form(context, nodelist, *args, **kwargs):
    '''
    This block tag can create or process forms either to create or to modify arguments.
    Usage is as follows:

    {% pp_argument_form POST=request.POST path=request.path issue=pp-issue.issue arg = pp_argumentation.argument%}
       Do stuff with {{ pp_argument.form }}.
    {% endpp_argument_form %}
    '''
    
    context.push()
    namespace = get_namespace(context)

    POST  = kwargs.get('POST', None)
    path  = kwargs.get('path', "")
    issue = kwargs.get('issue', None)
    arg = kwargs.get('arg', None)

    if POST and POST.get("form_id") == "pp_argument_form":
        form = ArgumentForm(POST) if arg is None else ArgumentForm(POST, instance=arg)
        if form.is_valid():
            new_arg = form.save(commit=False)
            #new_arg.author = request.user
            new_arg.parent = issue
            new_arg.pub_date = datetime.datetime.now()
            new_arg.save()
        new_arg = form.save()
        raise HttpRedirectException(HttpResponseRedirect(path))
    else:
        form = ArgumentForm() if arg is None else ArgumentForm(instance=arg)
        
    namespace['form'] = form
    output = nodelist.render(context)
    context.pop()
        
class ArgumentForm(forms.ModelForm):
    class Meta:
        model = Argument
        fields = ('name','text','arg_type',)

    form_id = forms.CharField(widget=forms.HiddenInput(), initial="pp_argument_form")
		
		

